import { nextTick, onUnmounted, ref, unref, watch } from 'vue';
import type {
  DynamicProps,
  FormActionType,
  FormProps,
  FormSchema,
  NamePath,
  Nullable,
  Recordable,
  UseFormReturnType,
} from '../types/form';
import { ElMessage } from 'element-plus';
import { getDynamicProps } from '../common/gloab';
type Props = Partial<DynamicProps<FormProps>>;

export function useForm(props?: Props): UseFormReturnType {
  const formRef = ref<Nullable<FormActionType>>(null);
  const loadedRef = ref<Nullable<boolean>>(false);

  async function getForm() {
    const form = unref(formRef);
    if (!form) {
      ElMessage({
        message: '获取formRef失败！',
        type: 'error',
        duration: 2000,
      });
    }
    await nextTick();
    return form as FormActionType;
  }

  function register(instance: FormActionType) {
    onUnmounted(() => {
      formRef.value = null;
      loadedRef.value = null;
    });
    // console.log("11111111111111111")

    if (unref(loadedRef) && instance === unref(formRef)) return;

    formRef.value = instance;
    loadedRef.value = true;
    // console.log("2222222222222222222222")

    watch(
      () => props,
      () => {
        props && instance.setProps(getDynamicProps(props));
      },
      {
        immediate: true,
        deep: true,
      },
    );
  }
  const methods: FormActionType = {
    // 重置
    // resetFields: async () => {
    //   const form = await getForm()
    //   form.resetFields()
    // },
    resetFields: async () => {
      await getForm().then(async (form) => {
        await form.resetFields();
      });
    },
    setProps: async (formProps: Partial<FormProps>) => {
      const form = await getForm();
      form.setProps(formProps);
    },
    setFieldsValue: async (values: Recordable) => {
      const form = await getForm();
      form.setFieldsValue(values);
    },

    getFieldsValue: <T>() => {
      return unref(formRef)?.getFieldsValue() as T;
    },
    clearValidate: async (name?: string | string[]) => {
      const form = await getForm();
      form.clearValidate(name);
    },
    validate: async (nameList?: NamePath[]): Promise<Recordable> => {
      const form = await getForm();
      return form.validate(nameList);
    },
    validateField: async (name?: string | undefined) => {
      const form = await getForm();
      form.validateField(name);
    },
    updateSchema: async (data: Partial<FormSchema> | Partial<FormSchema>[]) => {
      const form = await getForm();
      form.updateSchema(data);
    },
    appendSchemaByField: async (
      schema: FormSchema | FormSchema[],
      prefixField?: string | undefined,
      first?: boolean,
    ) => {
      const form = await getForm();
      form.appendSchemaByField(schema, prefixField, first);
    },
    removeSchemaByField: async (field: string | string[]) => {
      unref(formRef)?.removeSchemaByField(field);
    },
  };
  return [register, methods];
}
